package com.woniu.woniuk16.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.woniuk16.dto.WoniuUserDetails;
import com.woniu.woniuk16.entity.WoniuAccount;
import com.woniu.woniuk16.mapper.WoniuResourceMapper;
import com.woniu.woniuk16.service.WoniuAccountService;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Data
public class LoadAccountServiceImpl implements UserDetailsService {

    @Autowired
    private WoniuAccountService was;
    @Resource
    private WoniuResourceMapper woniuResourceMapper;

    @Autowired
    private RedisTemplate<String,Object> rtl;
    /*
      就是通过账号名加载账号对象的方法
      加载上来的账号对象必须是统一的一种类型UserDetails，所以我们需要自定义一个类来实现该接口
      这个类是WoniuUserDetails
    */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        WoniuAccount wa = was.getOne(
                new QueryWrapper<WoniuAccount>().eq("account_name", username));
        if(wa == null) {
            throw new UsernameNotFoundException("没有该账号");
        }
        WoniuUserDetails wud = new WoniuUserDetails();
        BeanUtils.copyProperties(wa, wud);



        List<String> url = woniuResourceMapper.getUrl(wa.getAccountId());

        rtl.opsForValue().set("woniu:resource:"+wud.getAccountId(),url);
        rtl.expire("woniu:resource:"+wud.getAccountId(),30, TimeUnit.MINUTES);

        return wud;
    }

}